package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper , AdUser> implements AdUserService {
    @Override
    public ResponseResult login(UserDto userDto) {
        if (userDto.getUsername() == null || userDto.getPassword() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "请输入用户名或密码");
        }
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName , userDto.getUsername());
        List<AdUser> list = list(wrapper);
        if(list != null && list.size() == 1){
            AdUser user = list.get(0);
            String pas = DigestUtils.md5DigestAsHex((userDto.getPassword()+user.getSalt()).getBytes());
            if (user.getPassword().equals(pas)){
                Map map = new HashMap();
                user.setPassword("");
                user.setSalt("");
                map.put("token" , AppJwtUtil.getToken(user.getId().longValue()));
                map.put("user" , user);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
    }
}
